#include "tilted_twap.h"
#include <algorithm>

#include <iostream>
using namespace std;

tilted_twap::tilted_twap (const std::string& _name, const std::string& _symbol, int hs, int ms, int ss, int he, int me, int se, int _exec, int _num_shares, int _total_trades, double _finish_price, double _stop_price, int _trade_interval_spread, int _trade_size_spread) 
: bot (_name, _symbol, hs, ms, ss, he, me, se, _exec, _num_shares, _finish_price, _stop_price), rnd_interval (-_trade_interval_spread / 100., _trade_interval_spread / 100.0), rnd_size (-_trade_size_spread / 100., _trade_size_spread / 100.0), crv ("twap.crv"), editor ("twap.ed"), lsnr (&sol), lib ("twap.lib")
{
  
  total_trades = _total_trades;
  trade_interval = avail_time * 1. / total_trades;
  
  TWAP = 0;
  
  sol (&crv);
  editor.add (&crv, &lsnr);
  editor.attach_library (&lib);
  pviewer = &editor;
  
  
}

tilted_twap::~tilted_twap () {
  editor.save ();
  //crv.save ("twap.crv");
}

int tilted_twap::run (double secs) {
  
  if (bot::run (secs)) {
    //cout << "tilted_twap = " << (value * 1. / position) << endl;
  }
  
  return 1;
  
}

int tilted_twap::get_trade_size (double t) {
  double T = (t - start_time) * avail_time_1;
  trade_size = max (0, (int) (num_shares * sol (T) / 100. - position));
  int iT = (int) T;
  if (iT == 1) {
    return trade_size; 
  } else {
    return (max (0, (int) (trade_size + rnd_size () * trade_size))); 
  }
}

double tilted_twap::get_trade_interval () {
  return (max (0.01, trade_interval + rnd_interval () * trade_interval));
}
